using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;
using Util.Config;
using Util.Helper;

namespace Util.DataBase
{
    public class MySqlContext : IContext
    {
        /// <summary>
        /// 获得数据库访问实例
        /// </summary>
        /// <param name="bol_share_thread">实例是否共享线程</param>
        /// <param name="connKey">连接字符串的键值</param>
        /// <returns></returns>
        public SqlSugarClient GetDbContext(bool bol_share_thread, string connKey)
        {
            SqlSugarClient db;
            db = new SqlSugarClient(
                new ConnectionConfig()
                {
                    ConnectionString = AppSettingConfig.GetConnectionString(connKey ?? "DbConn"),//Config.Connection,
                    DbType = DbType.MySql,
                    IsAutoCloseConnection = true,
                    InitKeyType = InitKeyType.Attribute,
                    IsShardSameThread = bol_share_thread /*Shard Same Thread*/
                }
            );

            if (CommonSetting.PrintSqlOfSqlSugar)
            {
                //用于打印Sql语句
                db.Aop.OnLogExecuting = (sql, para) =>
                {
                    WriteLog(sql);
                };
            }

            return db;
        }


        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="message">日志内容</param>
        /// <returns></returns>
        private void WriteLog(string message)
        {
            var logHelper = NLogHelper.NLogHelperBuilder();
            logHelper.Info(message);
            //string path = $"Log/{jobNo}";
            //if (!Directory.Exists(path))
            //{
            //    Directory.CreateDirectory(path);
            //}
            //File.AppendAllText($"{path}/{DateTime.Now:yyyy-MM-dd}.log", $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}][{logType}]{message}\r\n");
        }
    }
}
